# ai_talk.py
import PySimpleGUI as sg
from openai import OpenAI
from rich.console import Console
from rich.markdown import Markdown

# 替换为你的key
api_key = 'your api key'
# AI对话界面布局
ai_dialog_layout = [
    [sg.Multiline(size=(100, 31), key='-AI_DIALOG-', disabled=True, font=("Microsoft YaHei", 12))],
    [sg.InputText(size=(90, 1), key='-AI_INPUT-', pad=4, font=("Microsoft YaHei", 12)), sg.Button('清空对话'),
     sg.Button('发送')]
]
client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")

messages = [{"role": "system", "content": "请使用中文回复,请回答系统工程领域范围的知识,包括运筹学,系统论,工程经济学,项目管理,质量管理等学科."}]


def chat_with_ai(window, values):
    user_input = values['-AI_INPUT-']
    if user_input:
        # 显示用户输入
        current_dialog = window['-AI_DIALOG-'].get()
        new_dialog = f"{current_dialog}你: {user_input}\n"
        window['-AI_DIALOG-'].update(new_dialog)

        # AI回显
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "请使用中文,并围绕Mem系统工程专业的知识领域进行回复"},
                {"role": "user", "content": user_input},
            ],
            stream=False
        )
        # 提取AI回复内容
        ai_response = response.choices[0].message.content

        # 使用 rich 渲染 Markdown
        console = Console(record=True)
        markdown = Markdown(ai_response)
        console.print(markdown)
        rendered_text = console.export_text()

        # 显示AI回复
        new_dialog = f"{new_dialog}欢乐豆: {rendered_text}\n"
        window['-AI_DIALOG-'].update(new_dialog)
        window['-AI_INPUT-'].update('')


def reset_dialog(window):
    # 清空对话框
    window['-AI_DIALOG-'].update('')
